package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.undo.CannotUndoException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
  //订单管理
@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;
    // 下单
    @Override
    public void submit(Order order) {
        // 获取登录人信息  实际项目中都要加非空判断
        User user = UserHolder.get();
        if (user==null) {
            throw new CustomException("登录人为空不能下单");
        }
        // 根据前端传过来的id查询收货地址
        Address address = addressMapper.selectById(order.getAddressId());
        if (address==null){
            throw new CustomException("收货地址为空");
        }
        //获取购物车列表
        List<Cart> cart = cartService.findCart();
        if (CollectionUtil.isEmpty(cart)){
            throw new CustomException("购物车为空不能下单");
        }
        //通过雪花算法生成id
        long id = IdWorker.getId();

        // 订单金额
        BigDecimal bigDecimal = new BigDecimal(0);

        // 遍历购物车
        for (Cart cart1 : cart) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id); //id
            orderDetail.setName(cart1.getName());// 名字
            orderDetail.setDishId(cart1.getDishId());// 菜品
            orderDetail.setSetmealId(cart1.getSetmealId());// 套餐
            orderDetail.setDishFlavor(cart1.getDishFlavor()); //口味
            orderDetail.setNumber(cart1.getNumber());// 数量
            orderDetail.setAmount(cart1.getAmount()); //金额
            orderDetail.setImage(cart1.getImage()); // 图片
            // mapper 保存
            orderDetailMapper.insert(orderDetail);
            //金额
            bigDecimal = bigDecimal.add(cart1.getAmount().multiply(new BigDecimal(cart1.getNumber())));
        }
        // 保存订单
        order.setId(id); // 订单id
        order.setNumber(String.valueOf(id)); // 订单号
        order.setStatus(1); // 待付款
        order.setUserId(user.getId()); // 下单用户id
        order.setOrderTime(new Date()); // 下单时间
        order.setCheckoutTime(new Date()); // 结账时间
        order.setAmount(bigDecimal); // 实收金额
        order.setUserName(user.getName()); // 下单用户名称
        order.setPhone(address.getPhone()); // 收货人手机号
        order.setAddress(address.getDetail()); // 收货人地址
        order.setConsignee(address.getConsignee()); // 收货人姓名
        // 5-2 mapper保存
        orderMapper.insert(order);

        // 6.清空购物车
        cartService.delete();




    }
    // 分页
    @Override
    public Page<Order> fenye(Integer pageNum, Integer pageSize, String number) {
        // 开启分页
        Page<Order> orderPage = new Page<>(pageNum, pageSize);
        // 构建条件
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.like(StrUtil.isNotBlank(number),Order::getNumber,number);

        orderPage = orderMapper.selectPage(orderPage, qw);


        return orderPage;
    }
      //  订单明细
      @Override
      public Page<Order> findByPage2(Long number, Date beginTime, Date endTime, Integer pageNum, Integer pageSize) {
        // 开启分页
          Page<Order> orderPage = new Page<>(pageNum, pageSize);
         //  构建条件
          LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
          qw.eq(number!=null,Order::getId,number); // id
          qw.ge(beginTime!=null,Order::getCheckoutTime,beginTime); //大于
          qw.le(endTime!=null,Order::getCheckoutTime,endTime); // 小于
           //设置时间排序
          qw.orderByDesc(Order::getOrderTime);
             // 查询
          orderPage = orderMapper.selectPage(orderPage, qw);
          List<Order> orderList = orderPage.getRecords();
          if (CollectionUtil.isNotEmpty(orderList)){
              for (Order order : orderList) {
                  //6. 根据订单id从详情表获取详情信息
                  LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                  wrapper1.eq(OrderDetail::getOrderId, order.getId());
                  List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                  order.setOrderDetails(orderDetailList);
              }
          }
          // 返回结果
          return orderPage;
      }
        // 历史订单
      @Override
      public Page<Order> lishidingdan(Integer pageNum, Integer pageSize) {
        // 开启分页
          Page<Order> page = new Page<>(pageNum, pageSize);
          // 构建条件
          LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
          qw.eq(Order::getUserId,UserHolder.get().getId());
          // 时间倒叙 就是时间早的在下面  时间晚的在上面
          qw.orderByDesc(Order::getCheckoutTime);
            // 执行查询
          page= orderMapper.selectPage(page, qw);
          List<Order> records = page.getRecords();
          if (CollectionUtil.isNotEmpty(records)){
              for (Order record : records) {
                  //6. 根据订单id从详情表获取详情信息
                  LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                  wrapper1.eq(OrderDetail::getOrderId, record.getId());
                  List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                  record.setOrderDetails(orderDetailList);
              }
          }
          return page;

      }


  }
